CODE FESTIVAL 2017 qual B C - 3 Steps
https://atcoder.jp/contests/code-festival-2017-qualb/tasks/code_festival_2017_qualb_c
解答
code: python
from collections import defaultdict
import sys
sys.setrecursionlimit(100000)
n, m = map(int, input().split())
ab = list(map(int, input().split())) for _ in range(m)
d = defaultdict(list)
for a, b in ab:
da.append(b)
db.append(a)
# n個の頂点の色を初期化。0:未着色、1:黒、-1:白
colors = 0 for _ in range(n+1)
def dfs(v, color):
colorsv = color
for to in dv:
if colorsto == color:
return False
if colorsto == 0 and not dfs(to, -color):
return False
return True
# 頂点 s と t の間に奇数長のパス(単純パスでなくても良い)が存在したとすると必ず s と t の間に辺が張られる
if dfs(1, 1): # 二部グラフである場合、辺を結ぶことができるのは色が異なる頂点間
black = 0
for i in colors:
if i == 1:
black += 1
white = n - black
# m := すでに結ばれている
print(black*white - m)
else: # 二部グラフでない場合、必ず奇数長のサイクルが存在するので全ての2頂点間のパスの中に奇数長のパスが存在する
# 任意の2頂点間を辺で結ぶ
print(n*(n-1)//2 - m)
テーマ
#graph
蟻本 2-5 二部グラフ判定
メモ
CODE FESTIVAL 2017 qualB C 3 Steps
うさぎでもわかる離散数学(グラフ理論) 第9羽 グラフの基礎3
CODE FESTIVAL 2017 qual B C問題 3 Steps
提出
code: python
from collections import defaultdict
from collections import deque
n, m = map(int, input().split())
ab = list(map(int, input().split())) for _ in range(m)
d = defaultdict(list)
for a, b in ab:
da.append(b)
db.append(a)
# print(d)
# defaultdict(<class 'list'>, {1: 2, 2: 1, 3, 3: 2, 4, 4: 3, 5, 5: 4, 6, 6: 5})
que = deque([])
que.append(([ab00], 0))
dist = -1 * (n+1)
while que:
to, dis = que.popleft()
for t in to:
if distt != -1:
continue
else:
dis += 1
distt = dis
que.append((dt, dis))
for idx, v in enumerate(dist):
if v == dist1 + 3:
d1.append(idx)
didx.append(1)
# print(dist)
# -1, 1, 2, 3, 4, 5, 6
# print(d)
# defaultdict(<class 'list'>, {1: 2, 4, 2: 1, 3, 3: 2, 4, 4: 3, 5, 1, 5: 4, 6, 6: 5})